package com.team7.happycommunity.propertymanagement.filter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.team7.happycommunity.propertymanagement.common.CommonResult;
import com.team7.happycommunity.propertymanagement.pojo.PropertyManage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

//@Component
//@WebFilter(urlPatterns = "/user/test2",filterName = "authFilter")
public class RegistorFilter implements Filter {

    @Value("${spring.application.name}")
    String applicationName;

    @Autowired
    RedisTemplate redisTemplate;

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        System.out.println("====filter====");
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        HttpSession httpSession = httpServletRequest.getSession();
        Cookie[] cookies = ((HttpServletRequest) servletRequest).getCookies();
        if(cookies == null){
            CommonResult commonResult = CommonResult.failed();
            servletResponse.setCharacterEncoding("UTF-8");
            servletResponse.setContentType("application/json; charset=utf-8");
            PrintWriter out = servletResponse.getWriter();
            out.append(JSONObject.toJSONString(commonResult));
        }else{
            String cookie_get = null;
            for(Cookie cookie :cookies){
                if (cookie.getName().equals("user")){
                    cookie_get = cookie.getValue();
                }
            }
            HashOperations hashOperations = redisTemplate.opsForHash();
            PropertyManage propertyManage = (PropertyManage)hashOperations.get("hash:"+applicationName+":user",cookie_get);
            System.out.println(propertyManage.toString());
            filterChain.doFilter(servletRequest,servletResponse);
            System.out.println("====filter====");
        }
//        PropertyManage propertyManage = (PropertyManage)hashOperations.get("hash:"+applicationName+":user",cookie);
//        System.out.println(propertyManage.toString());
//        filterChain.doFilter(servletRequest,servletResponse);
//        System.out.println("====filter====");

    }
}
